package com.college.common.utils.security;

import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class WyAesUtils {
    //加密方法
    public static String encode(String content, String key) {
        if (content == null || content.length() < 1) {
            return null;
        }
        try {
            Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            byte[] byteRresult = cipher.doFinal(byteContent);
            return byteToHexString(byteRresult);
        } catch (Exception e) {
            //
        }
        return null;
    }

    private static String byteToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    //AES方式初始化cipher
    private static Cipher initCipher(String key, int mode) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode, secretKeySpec);
        return cipher;
    }

    public static void main(String[] args) {
        System.out.println(encode("12345674567", "7bRfnTYdaTQ8DcCc4v4QEQ=="));
    }

    public static void request() {
        String appKey = "xxxxxx";
        String appSecret = "xxxxxx";
        String params = "{\"page\":1,\"pageSize\":20}";
        //org.apache.commons.codec.digest
        String sign = DigestUtils.md5Hex(params);
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String checksum = encode(appKey + sign + curtime, appSecret);
    }


}
